package com.illtamer.infinite.morii.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.illtamer.infinite.morii.mapper.MoriiObjectMapper;
import com.illtamer.infinite.morii.pojo.MoriiObject;
import com.illtamer.infinite.morii.util.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service
public class MoriiObjectService {

    @Resource(name = "moriiObjectMapper")
    private MoriiObjectMapper moriiObjectMapper;

    /**
     * 增
     * */
    public MoriiObject insert(MoriiObject moriiObject) {
        // 当 key 无缓存数据在库中时，此特判生效，并记录缓存
        MoriiObject old = query(moriiObject.getKey());
        if (old != null) {
            if (SecurityUtil.SHA1(old.getPom()).equals(SecurityUtil.SHA1(moriiObject.getPom()))
                    && SecurityUtil.SHA1(old.getJar()).equals(SecurityUtil.SHA1(moriiObject.getJar()))) {
                log.warn("Repeat data! Key: {}", moriiObject.getKey());
            } else update(moriiObject);
            return old;
        }
        moriiObjectMapper.insert(moriiObject);
        return moriiObject;
    }

    /**
     * 删
     * @param key groupId + / + artifactId + / + version
     * */
    public MoriiObject delete(String key) {
        QueryWrapper<MoriiObject> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(MoriiObject::getKey, key);
        moriiObjectMapper.delete(wrapper);
        return null;
    }

    /**
     * 改
     * @apiNote groupId artifactId version 相同，更新其余值
     * */
    public MoriiObject update(MoriiObject moriiObject) {
        UpdateWrapper<MoriiObject> wrapper = new UpdateWrapper<>();
        wrapper.lambda()
                .eq(MoriiObject::getPom, moriiObject.getPom())
                .eq(MoriiObject::getJar, moriiObject.getJar());
        moriiObjectMapper.update(null, wrapper);
        return moriiObject;
    }

    /**
     * 查
     * @param key groupId + / + artifactId + / + version
     * */
    // TODO cache
    public MoriiObject query(String key) {
        QueryWrapper<MoriiObject> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(MoriiObject::getKey, key);
        return moriiObjectMapper.selectOne(wrapper);
    }

}
